// policies/isLoggedIn.js
const config = require("../env.config").wechatConfig;
const isDevEnvironment = require('../env.config').isDevEnvironment;
const wechat4Dev = require('../env.config').wechat4Dev;
module.exports = function (req, res, proceed) {
  //判断是否有微信信息，没有的话先获取一下放到session中
  //表示是本地的环境
  if (isDevEnvironment){
    SessionUtil.setSessionValue(req,"wechat",wechat4Dev)
    return proceed();
  }
  if (!req.session.wechat) {
    let code = req.param('code')
    if (!code) {
      let url = encodeURIComponent(config.baseUrl+req.originalUrl);
      return res.redirect(config.proxyUrl+"?appId="+config.appid+"&appSecret="+config.secret+"&bUrl="+url);
    }
    WeChatService.getUserByCode(code,req,res).then(wechat => {
      SessionUtil.setSessionValue(req,"wechat",wechat)
      return proceed();
    }).catch(e => {
      sails.log.error(e)
      res.render('500', { message: '获取身份信息失败' })
    })
  }else{
    return proceed();
  }

  //TODO:该策略暂时保存，用于接收小程序交互的参数处理，目前为空
};
